import ddddocr
from PIL import Image, ImageDraw, ImageFont
import io
from fontTools.ttLib import TTFont

def get_font_maps(font_url):
    # 创建ddddocr
    ocr = ddddocr.DdddOcr(show_ad=False)
    # 创建字体映射表
    font_maps = {}
    # 获取特殊字体
    font = TTFont(font_url)
    for code, name in font.getBestCmap().items():
        if code == 120:
            continue
        else:
            # print(code, chr(code), name)
            # 1. 创建画布
            img = Image.new("RGB", (25, 25), (255, 255, 255))
            # 2. 指定字体
            img_font = ImageFont.truetype(font_url, 20)
            # 3. 绘制图片
            draw = ImageDraw.Draw(img)
            draw.text((0, 0), text=chr(code), fill=(0, 0, 0), font=img_font)
            # 4. 保存图片
            # img.save(f'./static/font/imgs/{code}.png', "png")
            # 创建内存字节流io.BytesIO()
            img_bytes = io.BytesIO()
            # 保存图片到内存字节流img.save(img_bytes, format="JPEG"), 避免磁盘I/O，速度更快
            img.save(img_bytes, format="JPEG")
            # classification识别图片二进制  img_bytes.getvalue()图片字节流转图片二进制
            r = ocr.classification(img_bytes.getvalue())
            # print(code, "识别结果", r)
            font_maps[code] = r
    print(f"字体映射表", font_maps)
    return font_maps


if __name__ == '__main__':
    get_font_maps("../static/font/file")

